#include <psp2common/types.h>

#include "font_cache.h"
#include "utils.h"

FontCacheListEntry *fontCacheListGetEntryByCharacter(FontCacheList *list, uint32_t ucs2)
{
    if (!list)
        return NULL;

    FontCacheListEntry *entry = list->head;

    while (entry)
    {
        if (entry->ucs2 == ucs2)
            return entry;
        entry = entry->next;
    }

    return NULL;
}

FontCacheListEntry *fontCacheListGetEntryByNumber(FontCacheList *list, int n)
{
    if (!list)
        return NULL;

    FontCacheListEntry *entry = list->head;

    while (n > 0 && entry)
    {
        n--;
        entry = entry->next;
    }

    if (n != 0)
        return NULL;

    return entry;
}

int fontCacheListRemoveEntry(FontCacheList *list, FontCacheListEntry *entry)
{
    if (!list || !entry)
        return 0;

    if (entry->previous)
        entry->previous->next = entry->next;
    else
        list->head = entry->next;

    if (entry->next)
        entry->next->previous = entry->previous;
    else
        list->tail = entry->previous;

    list->length--;

    if (entry->data_uid >= 0)
        SceFree(entry->data_uid);
    if (entry->entry_uid >= 0)
        SceFree(entry->entry_uid);

    if (list->length == 0)
    {
        list->head = NULL;
        list->tail = NULL;
    }

    return 1;
}

void fontCacheListAddEntry(FontCacheList *list, FontCacheListEntry *entry)
{
    if (!list || !entry)
        return;

    entry->next = NULL;
    entry->previous = NULL;

    if (list->head == NULL)
    {
        list->head = entry;
        list->tail = entry;
    }
    else
    {
        FontCacheListEntry *tail = list->tail;
        tail->next = entry;
        entry->previous = tail;
        list->tail = entry;
    }

    list->length++;
}

void fontCacheListEmpty(FontCacheList *list)
{
    if (!list)
        return;

    FontCacheListEntry *entry = list->head;

    while (entry)
    {
        FontCacheListEntry *next = entry->next;
        if (entry->data_uid >= 0)
            SceFree(entry->data_uid);
        if (entry->entry_uid >= 0)
            SceFree(entry->entry_uid);
        entry = next;
    }

    list->head = NULL;
    list->tail = NULL;
    list->length = 0;
}
